//
//  CXSearchViewController.m
//  CXShearchBar_Example
//
//  Created by caixiang on 2019/4/29.
//  Copyright © 2019年 caixiang305621856. All rights reserved.
//

#import "CXSearchViewController.h"
#import "CXSearchCollectionViewCell.h"
#import "CXSearchCollectionReusableView.h"
#import "CXSearchLayout.h"
#import "SearchResultVC.h"

@interface CXSearchViewController ()<UICollectionReusableViewButtonDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UITextFieldDelegate
>

@property (weak, nonatomic) IBOutlet UICollectionView *searchCollectionView;
@property (weak, nonatomic) IBOutlet UIView *TF_bgview;


@property (weak, nonatomic) IBOutlet UITextField *searchTextField;
@property (nonatomic, strong) NSMutableArray *dataSource;
//@property (nonatomic, strong) NSMutableArray *searchDataSource;
@property (strong, nonatomic) CXSearchLayout *searchLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *top;


@end

const CGFloat kMinimumInteritemSpacing = 10;
const CGFloat kFirstitemleftSpace = 20;

@implementation CXSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpUI];
    [self setUpdata];
}

- (void)setUpUI {
    self.navigationController.navigationBarHidden = YES;
    self.searchCollectionView.alwaysBounceVertical = YES;
    self.searchCollectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
    self.searchTextField.delegate = self;
    self.searchTextField.backgroundColor =[UIColor mainPlaceholdColor];
    self.searchTextField.keyboardType = UIKeyboardTypeDefault;
    self.searchTextField.returnKeyType = UIReturnKeySearch;
    [self.TF_bgview.layer setCornerRadius:12];
    [self.TF_bgview.layer setMasksToBounds:YES];
    self.searchCollectionView.dataSource = self;
    self.searchCollectionView.delegate = self;
    
    [self.searchCollectionView setCollectionViewLayout:self.searchLayout animated:YES];
    [self.searchCollectionView registerClass:[CXSearchCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([CXSearchCollectionReusableView class])];
    [self.searchCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([CXSearchCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([CXSearchCollectionViewCell class])];
}

- (void)setUpdata {
    WeakSelf;
    [ZTHttp http_mySearchHistory_success:^(NSDictionary * _Nullable dic) {
        if (dic) {
            NSArray * array = [dic objectForKey:@"data"];
            if (array.count>0 ) {
                weakSelf.dataSource = [NSString mj_objectArrayWithKeyValuesArray:array];
                [weakSelf.searchCollectionView reloadData];
            }
        }
    } failure_Nonnull:^(NSDictionary * _Nonnull dic) {
        ZTLog(@"请求失败");
    }];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([CXSearchCollectionViewCell class]) forIndexPath:indexPath];
}

#pragma mark - UICollectionViewDelegate
- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
//    NSInteger section = indexPath.section;
    NSInteger item = indexPath.item;
    
    CXSearchCollectionViewCell * searchCollectionViewCell = (CXSearchCollectionViewCell *)cell;
    NSString * sting = self.dataSource[item];
    searchCollectionViewCell.text = sting;
};

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *reusableview = nil;
    if ([kind isEqualToString: UICollectionElementKindSectionHeader]){
        CXSearchCollectionReusableView* searchCollectionReusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([CXSearchCollectionReusableView class]) forIndexPath:indexPath];
        searchCollectionReusableView.delegate = self;
        searchCollectionReusableView.text = @"搜索历史";
//        searchCollectionReusableView.imageName = @"delete_img";
        searchCollectionReusableView.hidenDeleteBtn = NO;
        reusableview = searchCollectionReusableView;
    }
    return reusableview;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger item = indexPath.item;
    
    NSString * string = self.dataSource[item];
    return [CXSearchCollectionViewCell getSizeWithText:string];
    
    return CGSizeMake(80, 24);
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    NSInteger section = indexPath.section;
    NSInteger item = indexPath.item;
    NSString * string =  self.dataSource[item];
    //点击跳转
    [self pushTOResultVC:string];
}

-(void)pushTOResultVC:(NSString * )str{

    SearchResultVC * resultVC = [[SearchResultVC alloc]init];
    resultVC.keyword = str;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:resultVC animated:YES];
}

#pragma mark - textField
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if ([textField.text isEqualToString:@""]){
        return NO;
    }else{
        [self pushTOResultVC:textField.text];
        [textField resignFirstResponder];
        return YES;
    }
    
}

- (void)reloadData:(NSString *)textString {
//    CXSearchModel *searchModel = [[CXSearchModel alloc] initWithName:textString searchId:@""];
//    [self.searchDataSource addObject:searchModel];
//    //存数据
//    [CXDBTool saveStatuses:[self.searchDataSource copy] key:kHistoryKey];
//    [self.searchCollectionView reloadData];
//    self.searchTextField.text = @"";
}

- (IBAction)cancleClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UICollectionReusableViewButtonDelegate
- (void)deleteDatas:(CXSearchCollectionReusableView *)view {
    [ZTHttp http_clearSearchHistory_success:^(NSDictionary * _Nullable dic) {
        if (dic) {
            [self.dataSource removeAllObjects];
            [self.searchCollectionView reloadData];
        }
    } failure_Nonnull:^(NSDictionary * _Nonnull dic) {
        ZTLog(@"清空搜索记录失败，稍后再试");
    }];

}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (CXSearchLayout *)searchLayout{
    if (!_searchLayout) {
        _searchLayout = [[CXSearchLayout alloc] init];
        _searchLayout.headerReferenceSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 30);
        _searchLayout.minimumInteritemSpacing = kMinimumInteritemSpacing;
        _searchLayout.minimumLineSpacing = kMinimumInteritemSpacing;
        _searchLayout.listItemSpace = kMinimumInteritemSpacing;
        _searchLayout.sectionInset = UIEdgeInsetsMake(20, kFirstitemleftSpace, 0, kFirstitemleftSpace);
    }
    return _searchLayout;
}

@end
